/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.doodle.common.utils;

import android.graphics.Bitmap;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

public class BitmapPool {
	
    private ArrayList<WeakReference<Bitmap>> mPool;
    
    private static BitmapPool sPool[] = new BitmapPool[] {
    	new BitmapPool(), new BitmapPool(), new BitmapPool()
    };

    // Construct a BitmapPool which caches bitmap with any size;
    public BitmapPool() {
        mPool = new ArrayList<WeakReference<Bitmap>>();
    }
    
    // Get a Bitmap from the pool with the specified size.
    public synchronized Bitmap getBitmap(int width, int height) {
		for (int i = mPool.size() - 1; i >= 0; --i) {
			WeakReference<Bitmap> ref = mPool.get(i);
    		if (ref.get() != null) {
    			Bitmap bitmap = ref.get();
    			if (bitmap.getWidth() == width && bitmap.getHeight() == height) {
    				mPool.remove(i);
    				return bitmap;
    			}
    		} else {
    			mPool.remove(ref);
    		}
		}
    	return null;
    }
    
    // Put a Bitmap into the pool, if the Bitmap has a proper size. Otherwise
    // the Bitmap will be recycled. If the pool is full, an old Bitmap will be
    // recycled.
    public void recycle(Bitmap bitmap) {
        if (bitmap == null) return;
        
        synchronized(this) {
        	for (int i = mPool.size() - 1; i >= 0; --i) {
        		WeakReference<Bitmap> ref = mPool.get(i);
        		if (ref.get() == null) {
        			mPool.remove(i);
        		}
        	}
        	mPool.add(new WeakReference<Bitmap>(bitmap));
        }
    }

    
    public static BitmapPool getPool(int type) {
    	return sPool[type];
    }
    
    @Deprecated
    public synchronized void clear() {
    }
    @Deprecated
    public static void clearAll() {
    }
    @Deprecated
    public static void setRecycle(boolean recycle) {
    }
}
